import React, { FC, useEffect, useState } from 'react';
import { calculateQuestion, purgeQuestion } from '../utils';

type MathQuestionProps = {
  question: string,
  isCalculation: boolean,
  isPurge: boolean,
}

export const MathQuestion: FC<MathQuestionProps> = ({ question, isCalculation, isPurge }: MathQuestionProps) => {
  const [result, setResult] = useState('');
  const [compactText, setCompactText] = useState('');
  const [last, setLast] = useState('');
  const [highlight, setHighlight] = useState(false);
  
  // @ts-ignore
  useEffect(() => {
    if (highlight) {
      let timer = setTimeout(() => {
        setHighlight(false);
      }, 3000);
      
      return () => {
        timer && clearTimeout(timer);
      };
    }
  }, [highlight]);
  
  useEffect(() => {
    if (last === '' || last !== result) {
      setLast(result);
      if (last !== '') {
        setHighlight(true);
      }
    }
  }, [result]);
  
  useEffect(() => {
    setCompactText(purgeQuestion(question));
  }, [question]);
  
  useEffect(() => {
    if (isCalculation) {
      setResult(calculateQuestion(question));
    }
  }, [question, isCalculation]);
  
  return (
    <div className={'math-question' + (highlight ? ' highlight' :  '')}>
      <div className={'question'}>
        {isPurge ? compactText : question}
      </div>
      {isCalculation && result ? (<div className='result'>{result}</div>) : null}
    </div>
  );
};

type MathQuestionsProps = {
  questions: string[],
  columns: number,
  // isCalculation: boolean,
  isPurge?: boolean,
  // children: React.ReactNode
}

const rangeSize = (start: number, size: number): number[] => {
  const range = [];
  for (let i = 0; i < size; i++) {
    range.push(start + i);
  }
  return range;
};

export const MathQuestions: FC<MathQuestionsProps> = ({
  questions, columns = 3, isPurge: inputPurge,
}: MathQuestionsProps): JSX.Element => {
  
  const [isCalculation, setCalculation] = useState(false);
  const [isPurge, setPurge] = useState(false);
  
  useEffect(() => {
    setPurge(!!inputPurge);
  }, [inputPurge]);
  
  const style = {
    width: 100 / columns + '%',
  };
  
  const rows = Math.ceil(questions.length / columns);
  
  return (
    <div>
      <table width='100%'>
        {rangeSize(0, rows).map(r => (
          <tr>{rangeSize(0, columns).map(i => {
            const q = questions[r * columns + i] || '';
            return <td style={style}><MathQuestion isPurge={isPurge} isCalculation={isCalculation} question={q}/></td>;
          })}</tr>
        ))}
      </table>
      <div className='actions'>
        <button type='button' onClick={() => setCalculation(!isCalculation)}>
          {isCalculation ? '隐藏' : '显示'}计算结果
        </button>
        <button type='button' onClick={() => setPurge(!isPurge)}>
          {isPurge ? '隐藏' : '显示'}紧凑模式
        </button>
      </div>
      <p>
        紧凑模式：替换中文字符的 <code>＋</code> <code>－</code> <code>（</code> <code>）</code> 为英文字符串
      </p>
    </div>
  );
};